<?php

/*
 +-----------------------------------------------------------------------+
 | plugins/sieverules/edit_sieverule.inc                                 |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |	 Displays form to add/edit a sieve rule                              |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Philip Weir                                                   |
 +-----------------------------------------------------------------------+
 | Requires: plugins/sauserprefs/sieverules_func.inc                     |
 +-----------------------------------------------------------------------+

 $Id: $

*/

require_once('plugins/sieverules/sieverules_func.inc');

$OUTPUT->set_pagetitle(rcube_label(($RCMAIL->action=='add-sieverule' ? 'newfilter' : 'edititem')));
$OUTPUT->add_handlers(array('sieveruleslist' => 'rcmail_sieverules_list',
							'sieveruleform' => 'rcmail_sieverules_form'));
$OUTPUT->include_script('list.js');
$OUTPUT->include_script('sieverules.js');
$OUTPUT->add_label('norulename', 'ruleexists', 'noheader', 'headerbadchars','noheadervalue',
					'sizewrongformat', 'noredirect', 'redirectaddresserror', 'noreject','vacnodays',
					'vacdayswrongformat', 'vacnosubject', 'vacnomsg', 'notifynomothod',
					'notifynomsg', 'filterdeleteconfirm', 'ruledeleteconfirm', 'actiondeleteconfirm');
$OUTPUT->send('editsieverule');

function rcmail_sieverules_form($attrib) {
	global $RCMAIL, $OUTPUT, $SIEVE, $SCRIPT, $sieverules_config;
	$ext = $SIEVE->get_extensions();

	$iid = get_input_value('_iid', RCUBE_INPUT_GPC);
	if ($iid == '')
		$iid = sizeof($SCRIPT);

	$cur_script = $SCRIPT[$iid];
	$OUTPUT->set_env('iid', $iid);

	if (sizeof($sieverules_config['predefined_rules']) > 0) {
		$predefined = array();
		foreach($sieverules_config['predefined_rules'] as $idx => $data)
			array_push($predefined, array($data['type'], $data['header'], $data['operator'], $data['target']));

		$OUTPUT->set_env('predefined_rules', $predefined);
	}

	list($form_start, $form_end) = get_form_tags($attrib, 'save-sieverule');
	unset($attrib['form']);

	$out = $form_start;

	$hidden_iid = new html_hiddenfield(array('name' => '_iid', 'value' =>  $iid));
	$out .= $hidden_iid->show();

	// 'any' flag
	if (sizeof($cur_script['tests']) == 1 && $cur_script['tests'][0]['type'] == 'true' && !$cur_script['tests'][0]['not'])
		$any = true;

    // filter disable
	$field_id = 'rcmfd_disable';
	$input_disable = new html_checkbox(array('name' => '_disable', 'id' => $field_id, 'value' => 1));

	$out .= html::span('disableLink', html::label($field_id, Q(rcube_label('disablerule')))
			 . "&nbsp;" . $input_disable->show($cur_script['disabled']));

	// filter name input
	$field_id = 'rcmfd_name';
	$input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id));

    $out .= html::label($field_id, Q(rcube_label('filtername')));
    $out .= "&nbsp;" . $input_name->show($cur_script['name']);

	$out .= "<br /><br />";

	if (sizeof($cur_script['tests']) == 1 && $cur_script['tests'][0]['type'] == 'true' && !$cur_script['tests'][0]['not'])
		$join_any = true;

	$field_id = 'rcmfd_join_all';
	$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof', 'onclick' => 'rule_join_radio(\'allof\')'));
	$join_type = $input_join->show($cur_script['join'] && !$join_any ? 'allof' : '');
	$join_type .= "&nbsp;" . html::label($field_id, Q(rcube_label('filterallof')));

	$field_id = 'rcmfd_join_anyof';
	$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof', 'onclick' => 'rule_join_radio(\'anyof\')'));
	$join_type .= "&nbsp;" . $input_join->show($cur_script['join'] && !$join_any ? '' : 'anyof');
	$join_type .= "&nbsp;" . html::label($field_id, Q(rcube_label('filteranyof')));

	$field_id = 'rcmfd_join_any';
	$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any', 'onclick' => 'rule_join_radio(\'any\')'));
	$join_type .= "&nbsp;" . $input_join->show($join_any ? 'any' : '');
	$join_type .= "&nbsp;" . html::label($field_id, Q(rcube_label('filterany')));

	$rules_table = new html_table(array('id' => 'rules-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 5));
    $rules_table = rule_row($ext, $rules_table, null, $sieverules_config['predefined_rules'], $attrib);

    if (!$join_any) {
	    if (!isset($cur_script))
	    	$rules_table = rule_row($ext, $rules_table, array(), $sieverules_config['predefined_rules'], $attrib);
	    else foreach ($cur_script['tests'] as $rules)
	    	$rules_table = rule_row($ext, $rules_table, $rules, $sieverules_config['predefined_rules'], $attrib);
	}

	$out .= html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('messagesrules')))
			 . Q(rcube_label('sieveruleexp')) . "<br /><br />"
			 . $join_type . "<br /><br />"
			 . $rules_table->show($attrib));

	$RCMAIL->imap_init(TRUE);
	$actions_table = new html_table(array('id' => 'actions-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 3));
    $actions_table = action_row($ext, $actions_table, 'rowid', null, $attrib);

    if (!isset($cur_script))
    	$actions_table = action_row($ext, $actions_table, 0, array(), $attrib);
    else foreach ($cur_script['actions'] as $idx => $actions)
    	$actions_table = action_row($ext, $actions_table, $idx, $actions, $attrib);

	$out .= html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('messagesactions')))
			. Q(rcube_label('sieveactexp')). "<br /><br />"
			. $actions_table->show($attrib));

	$out .= $form_end;

	return $out;
}

function rule_row($ext, $rules_table, $rule, $predefined_rules, $attrib) {
	global $sieverules_config;
	$imgclass = null;

	if (!isset($rule)) {
		$rules_table->set_row_attribs(array('style' => 'display: none;'));
		$imgclass = 'nohtc';
	}

	$headers = array('subject' => 'header::Subject',
  					'from' => 'address::Sender',
  					'to' => 'address::To',
  					'cc' => 'address::Cc',
  					'bcc' => 'address::Bcc',
  					'envelopeto' => 'envelope::To',
  					'envelopefrom' => 'envelope::From',
  					);

	$operators = array('filtercontains' => 'contains',
  					'filternotcontains' => 'notcontains',
  					'filteris' => 'is',
  					'filterisnot' => 'notis',
  					'filterexists' => 'exists',
  					'filternotexists' => 'notexists'
  					);

  	if (in_array('regex', $ext) || in_array('relational', $ext) || in_array('subaddress', $ext))
  		$operators['filteradvoptions'] = 'advoptions';

	$header_style = 'visibility: hidden;';
	$op_style = '';
	$sizeop_style = 'display: none;';
	$target_style = '' ;
	$units_style = 'display: none;';

	$test = 'header';
	$selheader = 'Subject';
	$header = 'Subject';
	$op = 'contains';
	$sizeop = 'under';
	$target = '';
	$target_size = 150;
	$units = 'KB';

	$predefined = -1;
	foreach($predefined_rules as $idx => $data) {
		if (($data['type'] == $rule['type'] || $rule['type'] == 'exists')
			&& $data['header'] == $rule['header']
			&& $data['operator'] == ($rule['not'] ? 'not' : '') . $rule['operator']
			&& $data['target'] == $rule['target']) {
				$predefined = $idx;
				break;
		}
	}

	if ($predefined > -1) {
		$op_style = 'display: none;';
		$target_style = 'display: none;' ;
		$selheader = $rule['type'] . '::predefined_' . $predefined;
		$test = $rule['type'];

		if ($rule['type'] == 'size') {
			$header = 'size';
			$sizeop = $rule['operator'];
			preg_match('/^([0-9]+)(K|M|G)*$/', $rule['target'], $matches);
			$target = $matches[1];
			$target_size = 100;
			$units = $matches[2];
		}
		elseif ($rule['type'] == 'exists') {
			$selheader = $predefined_rules[$predefined]['type'] . '::predefined_' . $predefined;
			$header = $rule['header'];
			$op = ($rule['not'] ? 'not' : '') . $rule['operator'];
		}
		else {
			$header = $rule['header'];
			$op = ($rule['not'] ? 'not' : '') . $rule['operator'];
			$target = htmlspecialchars($rule['target']);
		}
	}
	elseif ((isset($rule['type']) && $rule['type'] != 'exists') && in_array($rule['type'] . '::' . $rule['header'], $headers)) {
		$target_style = $rule['operator'] == 'exists' ? 'display: none;' : '' ;

		$selheader = $rule['type'] . '::' . $rule['header'];
		$test = $rule['type'];
		$header = $rule['header'];
		$op = ($rule['not'] ? 'not' : '') . $rule['operator'];
		$target = htmlspecialchars($rule['target']);
	}
	elseif ((isset($rule['type']) && $rule['type'] == 'exists') && in_headerarray($rule['header'], $headers) != false) {
		$target_style = $rule['operator'] == 'exists' ? 'display: none;' : '' ;

		$selheader = in_headerarray($rule['header'], $headers) . '::' . $rule['header'];
		$test = $rule['type'];
		$header = $rule['header'];
		$op = ($rule['not'] ? 'not' : '') . $rule['operator'];
	}
	elseif (isset($rule['type']) && $rule['type'] == 'size') {
		$op_style = 'display: none;';
		$sizeop_style = '';
		$units_style = '';

		$selheader = 'size::size';
		$header = 'size';
		$sizeop = $rule['operator'];
		preg_match('/^([0-9]+)(K|M|G)*$/', $rule['target'], $matches);
		$target = $matches[1];
		$target_size = 100;
		$units = $matches[2];
	}
	elseif (isset($rule['type']) && $rule['type'] != 'true') {
		$header_style = '';
		$target_style = $rule['operator'] == 'exists' ? 'display: none;' : '' ;

		$selheader = 'header::other';
		$test = 'header';
		$header = $rule['header'];
		$op = ($rule['not'] ? 'not' : '') . $rule['operator'];
		$target = htmlspecialchars($rule['target']);
	}

	// check for advanced options
	$showadvanced = false;
	if (!in_array($op, $operators) || $rule['comparator'] != '') {
		$showadvanced = true;
		$target_style = 'display: none;';
	}

	$select_header = new html_select(array('name' => "_selheader[]", 'onchange' => 'header_select(this)'));
	foreach($headers as $name => $val) {
		if (($val == 'envelope' && in_array('envelope', $ext)) || $val != 'envelope')
			$select_header->add(Q(rcube_label($name)), Q($val));
	}

	foreach($predefined_rules as $idx => $data) {
		if (($data['type'] == 'envelope' && in_array('envelope', $ext)) || $data['type'] != 'envelope')
			$select_header->add(Q($data['name']), Q($data['type'] . '::predefined_' . $idx));
	}

	$select_header->add(Q(rcube_label('size')), Q('size::size'));
	$select_header->add(Q(rcube_label('otherheader')), Q('header::other'));
	$input_test = new html_hiddenfield(array('name' => '_test[]', 'value' => $test));
	$rules_table->add('selheader', $select_header->show($selheader) . $input_test->show());

	if (!empty($attrib['helpicon']))
		$help_button = html::img(array('src' => $attrib['helpicon'], 'alt' => rcube_label('sieveruleheaders'), 'border' => 0));
	else
		$help_button = rcube_label('sieveruleheaders');

	$help_button = html::a(array('name' => '_headerhlp', 'href' => "#", 'onclick' => 'return sieverule_xheaders(this);', 'title' => rcube_label('sieveruleheaders'), 'style' => $header_style), $help_button);

	$input_header = new html_inputfield(array('name' => '_header[]', 'size' => 15, 'style' => $header_style));
	$rules_table->add('header', $input_header->show($header) . "&nbsp;" . $help_button);

	$select_op = new html_select(array('name' => "_operator[]", 'onchange' => 'rule_op_select(this)', 'style' => $op_style . ' width: 123px;'));
	foreach($operators as $name => $val)
		$select_op->add(Q(rcube_label($name)), $val);

	$select_size_op = new html_select(array('name' => "_size_operator[]", 'style' => $sizeop_style . ' width: 123px;'));
	$select_size_op->add(Q(rcube_label('filterunder')), 'under');
	$select_size_op->add(Q(rcube_label('filterover')), 'over');

	if ($showadvanced)
		$rules_table->add('op', $select_op->show('advoptions') . $select_size_op->show($sizeop));
	else
		$rules_table->add('op', $select_op->show($op) . $select_size_op->show($sizeop));

	$input_target = new html_inputfield(array('name' => '_target[]', 'style' => $target_style . ' width: ' . $target_size . 'px'));

	$select_units = new html_select(array('name' => "_units[]", 'style' => $units_style));
	$select_units->add(Q(rcube_label('B')), '');
	$select_units->add(Q(rcube_label('KB')), 'K');
	$select_units->add(Q(rcube_label('MB')), 'M');

	$rules_table->add('target', $input_target->show($target) . "&nbsp;" . $select_units->show($units));

	if (!empty($attrib['addicon']))
		$add_button = html::img(array('class' => $imgclass, 'src' => $attrib['addicon'], 'alt' => rcube_label('addsieverule'), 'border' => 0));
	else
		$add_button = rcube_label('addsieverule');

	if (!empty($attrib['deleteicon']))
		$delete_button = html::img(array('class' => $imgclass, 'src' => $attrib['deleteicon'], 'alt' => rcube_label('deletesieverule'), 'border' => 0));
	else
		$delete_button = rcube_label('deletesieverule');

	$add_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_addrule(this);', 'title' => rcube_label('addsieverule')), $add_button);
	$delete_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_delrule(this);', 'title' => rcube_label('deletesieverule')), $delete_button);

	$rules_table->add('control', $add_button . "&nbsp;" . $delete_button);

	if (isset($rule))
		$rowid = $rules_table->size();
	else
		$rowid = 'rowid';

	$headers_table = new html_table(array('class' => 'records-table', 'cellspacing' => '0', 'style' => 'width: 100%;', 'cols' => 4));
	$headers_table->add(array('colspan' => 4, 'style' => 'white-space: normal;'), Q(rcube_label('sieveheadershlp')));
	$headers_table->add_row();

	$col1 = '';
	$col2 = '';
	$col3 = '';
	$col4 = '';
	sort($sieverules_config['other_headers']);
	$col_length = sizeof($sieverules_config['other_headers']) / 4;
	$col_length = ceil($col_length);
	foreach ($sieverules_config['other_headers'] as $idx => $xheader) {
		$input_xheader = new html_radiobutton(array('id' => $xheader . '_' . $rowid, 'name' => '_xheaders_' . $rowid  . '[]', 'value' => $xheader, 'onclick' => 'sieverule_set_xheader(this)'));
		$xheader_show = $input_xheader->show($header) . "&nbsp;" . html::label($xheader . '_' . $rowid, Q($xheader));

		if ($idx < $col_length)
			$col1 .= $xheader_show . "<br />";
		elseif ($idx < $col_length * 2)
			$col2 .= $xheader_show . "<br />";
    	elseif ($idx < $col_length * 3)
    		$col3 .= $xheader_show . "<br />";
    	elseif ($idx < $col_length * 4)
    		$col4 .= $xheader_show . "<br />";
	}

	$headers_table->add(array('style' => 'vertical-align: top; width: 25%;'), $col1);
	$headers_table->add(array('style' => 'vertical-align: top; width: 25%;'), $col2);
	$headers_table->add(array('style' => 'vertical-align: top; width: 25%;'), $col3);
	$headers_table->add(array('style' => 'vertical-align: top; width: 25%;'), $col4);

	$rules_table->set_row_attribs(array('style' => 'display: none;'));
	$rules_table->add(array('colspan' => 5), $headers_table->show());
	$rules_table->add_row();

	$advanced_table = new html_table(array('class' => 'records-table', 'cellspacing' => '0', 'style' => 'width: 100%;', 'cols' => 2));
	$advanced_table->add(array('colspan' => 2, 'style' => 'white-space: normal;'), Q(rcube_label('advancedoptions')));
	$advanced_table->add_row();

	$field_id = 'rcmfd_advoperator_'. $rowid;
	$select_advop = new html_select(array('id' => $field_id, 'name' => "_advoperator[]", 'style' => 'width: 268px', 'onchange' => 'rule_advop_select(this)'));

  	if (in_array('regex', $ext)) {
	  	$select_advop->add(Q(rcube_label('filterregex')), 'regex');
	  	$select_advop->add(Q(rcube_label('filternotregex')), 'notregex');
	}

  	if (in_array('relational', $ext)) {
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('isgreaterthan')), 'count "gt"');
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('isgreaterthanequal')), 'count "ge"');
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('islessthan')), 'count "lt"');
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('islessthanequal')), 'count "le"');
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('equals')), 'count "eq"');
	  	$select_advop->add(Q(rcube_label('count') . ' ' . rcube_label('notequals')), 'count "ne"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('isgreaterthan')), 'value "gt"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('isgreaterthanequal')), 'value "ge"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('islessthan')), 'value "lt"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('islessthanequal')), 'value "le"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('equals')), 'value "eq"');
	  	$select_advop->add(Q(rcube_label('value') . ' ' . rcube_label('notequals')), 'value "ne"');
	}

	if (in_array('subaddress', $ext)) {
	  	$select_advop->add(Q(rcube_label('userpart')), 'user');
	  	$select_advop->add(Q(rcube_label('notuserpart')), 'notuser');
	  	$select_advop->add(Q(rcube_label('detailpart')), 'detail');
	  	$select_advop->add(Q(rcube_label('notdetailpart')), 'notdetail');
	  	$select_advop->add(Q(rcube_label('domainpart')), 'domain');
	  	$select_advop->add(Q(rcube_label('notdomainpart')), 'notdomain');
	}

	$advanced_table->add(array('style' => 'white-space: normal;', 'class' => 'selheader'), html::label($field_id, Q(rcube_label('operator'))));
	$advanced_table->add(array('style' => 'white-space: normal;'), $select_advop->show($op));

	$field_id = 'rcmfd_comparator_'. $rowid;
	if (substr($op, 0, 5) == 'count' || substr($op, 0, 5) == 'value')
		$select_comparator = new html_select(array('id' => $field_id, 'name' => "_comparator[]", 'style' => 'width: 268px'));
	else
		$select_comparator = new html_select(array('id' => $field_id, 'name' => "_comparator[]", 'style' => 'width: 268px', 'disabled' => 'disabled'));
	$select_comparator->add(Q('i;ascii-casemap'), '');
	$select_comparator->add(Q('i;octet'), 'i;octet');

	foreach ($ext as $extension) {
		if (substr($extension, 0, 11) == 'comparator-')
			$select_comparator->add(Q(substr($extension, 11)), substr($extension, 11));
	}

	$advanced_table->add(array('style' => 'white-space: normal;', 'class' => 'selheader'), html::label($field_id, Q(rcube_label('comparator'))));
	$advanced_table->add(array('style' => 'white-space: normal;'), $select_comparator->show($rule['comparator']));

	$field_id = 'rcmfd_advtarget_'. $rowid;
	$input_advtarget = new html_inputfield(array('id' => $field_id, 'name' => '_advtarget[]', 'style' => 'width: 260px'));
	$advanced_table->add(array('style' => 'white-space: normal;', 'class' => 'selheader'), html::label($field_id, Q(rcube_label('teststring'))));
	$advanced_table->add(array('style' => 'white-space: normal;'), $input_advtarget->show($target));

	if (!$showadvanced)
		$rules_table->set_row_attribs(array('style' => 'display: none;'));
	$rules_table->add(array('colspan' => 5), $advanced_table->show());
	$rules_table->add_row();

	return $rules_table;
}

function action_row($ext, $actions_table, $rowid, $action, $attrib) {
	global $RCMAIL, $USER, $DB, $sieverules_config;
	static $a_mailboxes;
	$imgclass = null;

	if (!isset($action)) {
		$actions_table->set_row_attribs(array('style' => 'display: none;'));
		$imgclass = 'nohtc';
	}

	if (!empty($attrib['helpicon']))
		$help_icon = html::img(array('src' => $attrib['helpicon'], 'alt' => rcube_label('messagehelp'), 'border' => 0));
	else
		$help_icon = rcube_label('messagehelp');

	$folder_style = '';
	$redirect_style = 'display: none;';
	$reject_style = 'display: none;';
	$vac_style = 'display: none;';
	$imapflags_style = 'display: none;';
	$notify_style = 'display: none;';
	$vacadvstyle = 'display: none;';
	$vacshowadv = '';
	$noteadvstyle = 'display: none;';
	$noteshowadv = '';

	$method = 'fileinto';
	$folder = 'INBOX';
	$reject = '';
	$vacfrom = null;
	$vacto = null;
	$address = '';
	$days = '';
	$handle = '';
	$subject = '';
	$origsubject = '';
	$msg = '';
	$charset = RCMAIL_CHARSET;
	$flags = '';
	$nfrom = '';
	$nimpt = '';
	$nmethod = '';
	$noptions = '';
	$nmsg = '';

	if ($action['type'] == 'fileinto') {
		$method = 'fileinto';
		$folder = mod_mailbox($action['target'], 'out');
	}
	elseif ($action['type'] == 'reject') {
		$folder_style = 'display: none;';
		$reject_style = '';

		$method = 'reject';
		$reject = htmlspecialchars($action['target']);
	}
	elseif ($action['type'] == 'vacation') {
		$folder_style = 'display: none;';
		$vac_style = '';

		$method = 'vacation';
		$days = $action['days'];
		$vacfrom = $action['from'];
		$vacto = $action['addresses'];
		$handle = htmlspecialchars($action['handle']);
		$subject = htmlspecialchars($action['subject']);
		$origsubject = $action['origsubject'];
		$msg = htmlspecialchars($action['msg']);
		$charset = $action['charset'];

		// check advanced enabled
		if (!empty($vacfrom) || !empty($vacto) || !empty($handle) || $charset != RCMAIL_CHARSET) {
			$vacadvstyle = '';
			$vacshowadv = '1';
		}
	}
	elseif ($action['type'] == 'redirect') {
		$folder_style = 'display: none;';
		$redirect_style = '';

		$method = $action['type'];
		$address = $action['target'];
	}
	elseif ($action['type'] == 'imapflags') {
		$folder_style = 'display: none;';
		$imapflags_style = '';

		$method = $action['type'];
		$flags = $action['target'];
	}
	elseif ($action['type'] == 'notify') {
		$folder_style = 'display: none;';
		$notify_style = '';

		$method = 'notify';
		$nfrom = htmlspecialchars($action['from']);
		$nimpt = htmlspecialchars($action['importance']);
		$nmethod = $action['method'];
		$noptions = $action['options'];
		$nmsg = $action['msg'];

		// check advanced enabled
		if (!empty($nfrom) || !empty($nimpt)) {
			$noteadvstyle = '';
			$noteshowadv = '1';
		}
	}
	elseif ($action['type'] == 'discard' || $action['type'] == 'keep' || $action['type'] == 'stop') {
		$folder_style = 'display: none;';
		$method = $action['type'];
	}

	$select_action = new html_select(array('name' => "_act[]", 'onchange' => 'action_select(this)'));

	if (in_array('fileinto', $ext) && $sieverules_config['allowed_actions']['fileinto'])
		$select_action->add(Q(rcube_label('messagemoveto')), 'fileinto');
	if (in_array('vacation', $ext) && $sieverules_config['allowed_actions']['vacation'])
		$select_action->add(Q(rcube_label('messagevacation')), 'vacation');
	if (in_array('reject', $ext) && $sieverules_config['allowed_actions']['reject'])
		$select_action->add(Q(rcube_label('messagereject')), 'reject');
	if (in_array('imapflags', $ext) && $sieverules_config['allowed_actions']['imapflags'])
		$select_action->add(Q(rcube_label('messageimapflags')), 'imapflags');
	if (in_array('notify', $ext) && $sieverules_config['allowed_actions']['notify'])
		$select_action->add(Q(rcube_label('messagenotify')), 'notify');
	if ($sieverules_config['allowed_actions']['redirect'])
		$select_action->add(Q(rcube_label('messageredirect')), 'redirect');
	if ($sieverules_config['allowed_actions']['keep'])
		$select_action->add(Q(rcube_label('messagekeep')), 'keep');
	if ($sieverules_config['allowed_actions']['discard'])
		$select_action->add(Q(rcube_label('messagediscard')), 'discard');
	if ($sieverules_config['allowed_actions']['stop'])
		$select_action->add(Q(rcube_label('messagestop')), 'stop');

	$actions_table->add('action', $select_action->show($method));

	$vacs_table = new html_table(array('class' => 'records-table', 'cellspacing' => '0', 'cols' => 3, 'style' => $vac_style));

	$to_addresses = "";
	$vacto_arr = split(",", $vacto);
	$sql_result = $USER->list_identities();
	if ($DB->num_rows($sql_result)) {
		$field_id = 'rcmfd_sievevacfrom_'. $rowid;
	    $select_id = new html_select(array('id' => $field_id, 'name' => "_vacfrom[]", 'style' => 'width: 337px'));
		$select_id->add(Q(rcube_label('autodetect')), "");

	    while ($sql_arr = $DB->fetch_assoc($sql_result)) {
			$select_id->add($sql_arr['email'], $sql_arr['email']);

			$ffield_id = 'rcmfd_vac_' . $rowid . '_' . $sql_arr['identity_id'];
			$curaddress = in_array($sql_arr['email'], $vacto_arr) ? $sql_arr['email'] : "";
			$input_address = new html_checkbox(array('id' => $ffield_id, 'name' => '_vacto_check_' . $rowid . '[]', 'value' => $sql_arr['email'], 'onclick' => 'toggle_vac_to(this, '. $rowid .')'));
			$to_addresses .= $input_address->show($curaddress) . "&nbsp;" . html::label($ffield_id, Q($sql_arr['email'])) . "<br />";
		}
	}

	$vacs_table->set_row_attribs(array('class' => 'disabled', 'style' => 'display: none')); // 'style' => $vacadvstyle
	$vacs_table->add(null, html::label($field_id, Q(rcube_label('sievefrom'))));
	$vacs_table->add(array('colspan' => 2), $select_id->show($vacfrom));
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievevacto_'. $rowid;
	$input_vacto = new html_hiddenfield(array('id' => $field_id, 'name' => '_vacto[]', 'value' => $vacto));
	$vacs_table->set_row_attribs(array('class' => 'advanced', 'style' => $vacadvstyle));
	$vacs_table->add(array('style' => 'vertical-align: top;'), Q(rcube_label('sieveto')));
	$vacs_table->add(null, $to_addresses . $input_vacto->show());
	$help_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_help(this, ' . $vacs_table->size() . ');', 'title' => rcube_label('messagehelp')), $help_icon);
	$vacs_table->add(array('style' => 'vertical-align: top;'), $help_button);

	$vacs_table->set_row_attribs(array('class' => 'advhelp', 'style' => 'display: none;'));
	$vacs_table->add(array('colspan' => 3, 'class' => 'vacdaysexp'), rcube_label('vactoexp'));
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievevacdays_'. $rowid;
	$input_day = new html_inputfield(array('id' => $field_id, 'name' => '_day[]', 'style' => 'width: 310px'));
	$vacs_table->add(null, html::label($field_id, Q(rcube_label('days'))));
	$vacs_table->add(null, $input_day->show($days));
	$help_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_help(this, ' . $vacs_table->size() . ');', 'title' => rcube_label('messagehelp')), $help_icon);
	$vacs_table->add(null, $help_button);

	$vacs_table->set_row_attribs(array('style' => 'display: none;'));
	$vacs_table->add(array('colspan' => 3, 'class' => 'vacdaysexp'), rcube_label('vacdaysexp'));
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievevachandle_'. $rowid;
	$input_handle = new html_inputfield(array('id' => $field_id, 'name' => '_handle[]', 'style' => 'width: 310px'));
	$vacs_table->set_row_attribs(array('class' => 'disabled', 'style' => 'display: none')); // 'style' =>  $vacadvstyle
	$vacs_table->add(null, html::label($field_id, Q(rcube_label('sievevachandle'))));
	$vacs_table->add(null, $input_handle->show($handle));
	$help_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_help(this, ' . $vacs_table->size() . ');', 'title' => rcube_label('messagehelp')), $help_icon);
	$vacs_table->add(null, $help_button);

	$vacs_table->set_row_attribs(array('class' => 'advhelp', 'style' => 'display: none;'));
	$vacs_table->add(array('colspan' => 3, 'class' => 'vacdaysexp'), rcube_label('vachandleexp'));
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievevacsubject_'. $rowid;
	$input_subject = new html_inputfield(array('id' => $field_id, 'name' => '_subject[]', 'style' => 'width: 330px'));
	$vacs_table->add(array('style' => 'vertical-align: top;'), html::label($field_id, Q(rcube_label('subject'))));
	$field_id = 'rcmfd_sievevacsubject_orig_'. $rowid;
	$input_origsubject = new html_checkbox(array('id' => $field_id, 'value' => '1', 'onclick' => 'toggle_vac_osubj(this, '. $rowid .')'));
	$input_vacosubj = new html_hiddenfield(array('id' => 'rcmfd_sievevactoh_'. $rowid, 'name' => '_orig_subject[]', 'value' => $origsubject));
	$vacs_table->add(array('colspan' => 2), $input_subject->show($subject)); // . "<br />" . $input_origsubject->show($origsubject) . "&nbsp;" . html::label($field_id, Q(rcube_label('sieveorigsubj'))) . $input_vacosubj->show()
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievevacmag_'. $rowid;
	$input_msg = new html_textarea(array('id' => $field_id, 'name' => '_msg[]', 'rows' => '5', 'cols' => '40', 'style' => 'width: 330px'));
	$vacs_table->add('msg', html::label($field_id, Q(rcube_label('message'))));
	$vacs_table->add(array('colspan' => 2), $input_msg->show($msg));
	$vacs_table->add_row();

	$field_id = 'rcmfd_sievecharset_'. $rowid;
	$vacs_table->set_row_attribs(array('class' => 'advanced', 'style' => $vacadvstyle));
	$vacs_table->add(null, html::label($field_id, Q(rcube_label('charset'))));
	$vacs_table->add(array('colspan' => 2), charset_selector(array('id' => $field_id, 'name' => '_charset[]', 'style' => 'width: 337px'), $charset));
	$vacs_table->add_row();

	$input_advopts = new html_checkbox(array('id' => 'vadvopts' . $rowid, 'name' => '_vadv_opts[]', 'onclick' => 'sieverule_show_adv(this);', 'value' => '1'));
	$vacs_table->add(array('colspan' => '3', 'style' => 'text-align: right'), html::label('vadvopts' . $rowid, Q(rcube_label('advancedoptions'))) . $input_advopts->show($vacshowadv));

	$notify_table = new html_table(array('class' => 'records-table', 'cellspacing' => '0', 'cols' => 3, 'style' => $notify_style));

	$sql_result = $USER->list_identities();
	if ($DB->num_rows($sql_result)) {
		$field_id = 'rcmfd_sievenotifyfrom_'. $rowid;
	    $select_id = new html_select(array('id' => $field_id, 'name' => "_nfrom[]", 'style' => 'width: 337px'));
		$select_id->add(Q(rcube_label('autodetect')), "");

	    while ($sql_arr = $DB->fetch_assoc($sql_result))
			$select_id->add($sql_arr['email'], $sql_arr['email']);
	}

 	$notify_table->set_row_attribs(array('class' => 'disabled', 'style' => 'display: none')); // 'style' => $noteadvstyle
 	$notify_table->add(null, html::label($field_id, Q(rcube_label('sievefrom'))));
 	$notify_table->add(array('colspan' => 2), $select_id->show($nfrom));
 	$notify_table->add_row();

	$field_id = 'rcmfd_nmethod_'. $rowid;
	$input_method = new html_inputfield(array('id' => $field_id, 'name' => '_nmethod[]', 'style' => 'width: 330px'));
	$notify_table->add(null, html::label($field_id, Q(rcube_label('method'))));
	$notify_table->add(array('colspan' => 2), $input_method->show($nmethod));
	$notify_table->add_row();

	$field_id = 'rcmfd_noption_'. $rowid;
	$input_method = new html_inputfield(array('id' => $field_id, 'name' => '_noption[]', 'style' => 'width: 330px'));
	$notify_table->add(null, html::label($field_id, Q(rcube_label('options'))));
	$notify_table->add(array('colspan' => 2), $input_method->show($noptions));
	$notify_table->add_row();

	$field_id = 'rcmfd_nimpt_'. $rowid;
	$input_importance = new html_radiobutton(array('id' => $field_id . '_none', 'value' => 'none', 'onclick' => 'toggle_notify_impt(this, '. $rowid .')'));
	$importance_show = $input_importance->show($nimpt) . "&nbsp;" . html::label($field_id . '_none', Q(rcube_label('importancen')));
	$input_importance = new html_radiobutton(array('id' => $field_id . '_1', 'value' => '1', 'onclick' => 'toggle_notify_impt(this, '. $rowid .')'));
	$importance_show .= '&nbsp;&nbsp;' . $input_importance->show($nimpt) . "&nbsp;" . html::label($field_id . '_1', Q(rcube_label('importance1')));
	$input_importance = new html_radiobutton(array('id' => $field_id . '_2', 'value' => '2', 'onclick' => 'toggle_notify_impt(this, '. $rowid .')'));
	$importance_show .= '&nbsp;&nbsp;' . $input_importance->show($nimpt) . "&nbsp;" . html::label($field_id . '_2', Q(rcube_label('importance2')));
	$input_importance = new html_radiobutton(array('id' => $field_id . '_3', 'value' => '3', 'onclick' => 'toggle_notify_impt(this, '. $rowid .')'));
	$importance_show .= '&nbsp;&nbsp;' . $input_importance->show($nimpt) . "&nbsp;" . html::label($field_id . '_3', Q(rcube_label('importance3')));
	$input_importance = new html_hiddenfield(array('id' => 'rcmfd_sievenimpt_'. $rowid, 'name' => '_nimpt[]'));

	$notify_table->set_row_attribs(array('class' => 'disabled', 'style' => 'display: none'));  // 'style' => $noteadvstyle
	$notify_table->add(null, Q(rcube_label('flag')));
	$notify_table->add(array('colspan' => 2), $importance_show . $input_importance->show($nimpt));
	$notify_table->add_row();

	$field_id = 'rcmfd_nmsg_'. $rowid;
	$input_msg = new html_inputfield(array('id' => $field_id, 'name' => '_nmsg[]', 'style' => 'width: 330px'));
	$notify_table->add(null, html::label($field_id, Q(rcube_label('message'))));
	$notify_table->add(array('colspan' => 2), $input_msg->show($nmsg));
	$notify_table->add_row();

// 	$input_advopts = new html_checkbox(array('id' => 'nadvopts' . $rowid, 'name' => '_nadv_opts[]', 'onclick' => 'sieverule_show_adv(this);', 'value' => '1'));
// 	$notify_table->add(array('colspan' => '3', 'style' => 'text-align: right'), html::label('nadvopts' . $rowid, Q(rcube_label('advancedoptions'))) . $input_advopts->show($noteshowadv));

	// get mailbox list
	$mbox_name = $RCMAIL->imap->get_mailbox_name();

	// build the folders tree
	if (empty($a_mailboxes)) {
		// get mailbox list
		$a_folders = $RCMAIL->imap->list_mailboxes();
		$delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
		$a_mailboxes = array();

		foreach ($a_folders as $ifolder) {
			if (!empty($sieverules_config['folder_delimiter']))
				rcmail_build_folder_tree($a_mailboxes, str_replace($delimiter, $sieverules_config['folder_delimiter'], $ifolder), $sieverules_config['folder_delimiter']);
			else
				rcmail_build_folder_tree($a_mailboxes, $ifolder, $delimiter);
		}
	}

	$input_folderlist = new html_select(array('name' => '_folder[]', 'style' => $folder_style . ' width: 398px;'));
	rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, 100, $input_folderlist, false);

	$input_address = new html_inputfield(array('name' => '_redirect[]', 'style' => $redirect_style . ' width: 391px;'));
	$input_reject = new html_textarea(array('name' => '_reject[]', 'rows' => '5', 'cols' => '40', 'style' => $reject_style . ' width: 391px;'));
	$input_imapflags = new html_select(array('name' => '_imapflags[]', 'style' => $imapflags_style . ' width: 398px;'));
	$input_imapflags->add(Q(rcube_label('flagread')), Q('\\\\Seen'));
	$input_imapflags->add(Q(rcube_label('flagdeleted')), Q('\\\\Deleted'));
	$input_imapflags->add(Q(rcube_label('flaganswered')), Q('\\\\Answered'));
	$input_imapflags->add(Q(rcube_label('flagdraft')), Q('\\\\Draft'));
	$input_imapflags->add(Q(rcube_label('flagflagged')), Q('\\\\Flagged'));

	$actions_table->add('folder', $input_folderlist->show($folder) . $input_address->show($address) . $vacs_table->show() . $notify_table->show() . $input_imapflags->show($flags) . $input_reject->show($reject));

	if (!empty($attrib['addicon']))
		$add_button = html::img(array('class' => $imgclass, 'src' => $attrib['addicon'], 'alt' => rcube_label('addsieveact'), 'border' => 0));
	else
		$add_button = rcube_label('addsieveact');

	if (!empty($attrib['deleteicon']))
		$delete_button = html::img(array('class' => $imgclass, 'src' => $attrib['deleteicon'], 'alt' => rcube_label('deletesieveact'), 'border' => 0));
	else
		$delete_button = rcube_label('deletesieveact');

	$add_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_addaction(this);', 'title' => rcube_label('addsieveact')), $add_button);
	$delete_button = html::a(array('href' => "#", 'onclick' => 'return sieverule_delaction(this);', 'title' => rcube_label('deletesieveact')), $delete_button);

	if ($sieverules_config['multiple_actions'])
		$actions_table->add('control', $add_button . "&nbsp;" . $delete_button);
	else
		$actions_table->add('control', "&nbsp;");

	return $actions_table;
}

function in_headerarray($needle, $haystack) {
	foreach ($haystack as $data) {
		$args = split("::", $data);
		if ($args[1] == $needle)
			return $args[0];
	}

	return false;
}

function charset_selector($attrib, $charset) {
    $charsets = array(
        'US-ASCII'     => 'ASCII (English)',
        'EUC-JP'       => 'EUC-JP (Japanese)',
        'EUC-KR'       => 'EUC-KR (Korean)',
        'BIG5'         => 'BIG5 (Chinese)',
        'GB2312'       => 'GB2312 (Chinese)',
        'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
        'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
        'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
        'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
        'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
        'Windows-1251' => 'Windows-1251 (Cyrillic)',
        'Windows-1252' => 'Windows-1252 (Western)',
        'Windows-1255' => 'Windows-1255 (Hebrew)',
        'Windows-1256' => 'Windows-1256 (Arabic)',
        'Windows-1257' => 'Windows-1257 (Baltic)',
        'UTF-8'        => 'UTF-8'
        );

        $select = new html_select($attrib);
        $select->add(array_values($charsets), array_keys($charsets));

        return $select->show($charset);
}
?>